package com.yi.wood.web.interceptor;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.service.exception.BusinessException;
import com.yi.wood.service.po.UserCachePo;
import com.yi.wood.utils.StringTokenUtil;
import com.yi.wood.web.util.UserCacheUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author MoYi
 *
 */
@Component
public class AuthTokenInterceptor implements WebRequestInterceptor {

    @Resource
    private UserCacheUtil userCacheUtil;

    @Override
    public void preHandle(WebRequest webRequest){
        String token = webRequest.getHeader("Wood-Token");
        int tokenLength = 11;
        if (StringUtils.isEmpty(token) || token.length() < tokenLength) {
            throw new BusinessException(new Result(ResultCodeEnum.NO_TOKEN, null));
        }
        UserCachePo userCachePo = userCacheUtil.getUserByCache(StringTokenUtil.unPrefix(token));
        if (Objects.isNull(userCachePo)) {
            throw new BusinessException(new Result(ResultCodeEnum.AUTH_EXPIRE, null));
        }
        webRequest.setAttribute("userInfo", userCachePo, WebRequest.SCOPE_SESSION);
    }

    @Override
    public void postHandle(WebRequest webRequest, @Nullable ModelMap modelMap){

    }

    @Override
    public void afterCompletion(WebRequest webRequest, @Nullable Exception e){

    }
}

